package cn.wu.jishupeizhi.rabbitmq;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.time.LocalTime;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Topic {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    final String exchange = "topic.Exchange1";
    final String queueName1 = "topic.queue1";
    final String queueName2 = "topic.queue2";
    final String message = "hell111111o,every one!";

    //生产者
    @Test
    public void pushRabbitMq1() throws Exception {
        for (int i = 0; i < 100; i++) {
            rabbitTemplate.convertAndSend(exchange, "chine.news", message);
            Thread.sleep(20);
        }
    }

    //消费者
    /**
     * 该函数是一个RabbitMQ消息监听器，用于从指定的队列中消费消息。
     * 通过@RabbitListener注解配置了队列绑定信息，监听指定队列中的消息。
     * 当队列中有消息时，该函数会被触发，并将接收到的消息打印到控制台。
     *
     * @param receivedMessage 从RabbitMQ队列中接收到的消息内容。
     * @return 无返回值。
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = queueName1), // 绑定到指定名称的队列
            exchange = @Exchange(name = exchange, type = ExchangeTypes.TOPIC), // 绑定到指定名称和类型的交换机
            key = "#.news" // 使用通配符路由键匹配消息
    ))
    public void pullRabbitMq1(String receivedMessage) {
        // 打印接收到的消息内容及当前时间
        System.out.println("消费者1:" + receivedMessage + LocalTime.now());
    }

    //消费者
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = queueName2),
            exchange = @Exchange(name = exchange, type = ExchangeTypes.TOPIC),
            key = "chine.#"
    ))
    public void pullRabbitMq2(String receivedMessage) {
        System.out.println("消费者2:" + receivedMessage + LocalTime.now());
    }
}
